import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'dart:convert';

/// 数据库连接配置
class DbConnectionConfig {
  final String id;
  final String name;
  final String host;
  final int port;
  final String database;
  final String username;
  final String password;
  final String type; // mysql, postgresql, sqlite等
  final DateTime createdAt;
  final DateTime? lastUsedAt;

  DbConnectionConfig({
    required this.id,
    required this.name,
    required this.host,
    required this.port,
    required this.database,
    required this.username,
    required this.password,
    required this.type,
    required this.createdAt,
    this.lastUsedAt,
  });

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'host': host,
      'port': port,
      'database': database,
      'username': username,
      'password': password,
      'type': type,
      'createdAt': createdAt.toIso8601String(),
      'lastUsedAt': lastUsedAt?.toIso8601String(),
    };
  }

  factory DbConnectionConfig.fromJson(Map<String, dynamic> json) {
    return DbConnectionConfig(
      id: json['id'],
      name: json['name'],
      host: json['host'],
      port: json['port'],
      database: json['database'],
      username: json['username'],
      password: json['password'],
      type: json['type'],
      createdAt: DateTime.parse(json['createdAt']),
      lastUsedAt: json['lastUsedAt'] != null
          ? DateTime.parse(json['lastUsedAt'])
          : null,
    );
  }
}

/// 数据库连接管理器
class DbConnectionManager {
  static final DbConnectionManager _instance = DbConnectionManager._internal();
  factory DbConnectionManager() => _instance;
  DbConnectionManager._internal();

  final FlutterSecureStorage _storage = const FlutterSecureStorage();
  static const String _connectionsKey = 'db_connections';

  /// 保存连接配置
  Future<void> saveConnection(DbConnectionConfig config) async {
    try {
      final connections = await getAllConnections();
      connections[config.id] = config;
      await _saveAllConnections(connections);
    } catch (e) {
      throw Exception('保存连接配置失败: $e');
    }
  }

  /// 获取所有连接配置
  Future<Map<String, DbConnectionConfig>> getAllConnections() async {
    try {
      final jsonString = await _storage.read(key: _connectionsKey);
      if (jsonString == null || jsonString.isEmpty) {
        return {};
      }

      final Map<String, dynamic> jsonMap = json.decode(jsonString);
      final Map<String, DbConnectionConfig> connections = {};

      jsonMap.forEach((id, configJson) {
        connections[id] = DbConnectionConfig.fromJson(
            Map<String, dynamic>.from(configJson as Map));
      });

      return connections;
    } catch (e) {
      throw Exception('获取连接配置失败: $e');
    }
  }

  /// 根据ID获取连接配置
  Future<DbConnectionConfig?> getConnectionById(String id) async {
    final connections = await getAllConnections();
    return connections[id];
  }

  /// 删除连接配置
  Future<void> deleteConnection(String id) async {
    try {
      final connections = await getAllConnections();
      connections.remove(id);
      await _saveAllConnections(connections);
    } catch (e) {
      throw Exception('删除连接配置失败: $e');
    }
  }

  /// 更新最后使用时间
  Future<void> updateLastUsed(String id) async {
    final config = await getConnectionById(id);
    if (config != null) {
      final updatedConfig = DbConnectionConfig(
        id: config.id,
        name: config.name,
        host: config.host,
        port: config.port,
        database: config.database,
        username: config.username,
        password: config.password,
        type: config.type,
        createdAt: config.createdAt,
        lastUsedAt: DateTime.now(),
      );
      await saveConnection(updatedConfig);
    }
  }

  /// 保存所有连接配置
  Future<void> _saveAllConnections(
      Map<String, DbConnectionConfig> connections) async {
    final Map<String, dynamic> jsonMap = {};
    connections.forEach((id, config) {
      jsonMap[id] = config.toJson();
    });
    final jsonString = json.encode(jsonMap);
    await _storage.write(key: _connectionsKey, value: jsonString);
  }
}
